var path = require('path');
var webpack = require('webpack');
var projectName = require('./package').name;

module.exports = config => {
  var customLaunchers = {
    BS_Chrome: {
      base: 'BrowserStack',
      os: 'Windows',
      os_version: '10',
      browser: 'chrome',
      browser_version: '47.0'
    },
    BS_Firefox: {
      base: 'BrowserStack',
      os: 'Windows',
      os_version: '10',
      browser: 'firefox',
      browser_version: '43.0'
    },
    BS_Safari: {
      base: 'BrowserStack',
      os: 'OS X',
      os_version: 'El Capitan',
      browser: 'safari',
      browser_version: '9.0'
    },
    BS_MobileSafari8: {
      base: 'BrowserStack',
      os: 'ios',
      os_version: '8.3',
      browser: 'iphone',
      real_mobile: false
    },
    BS_MobileSafari9: {
      base: 'BrowserStack',
      os: 'ios',
      os_version: '9.1',
      browser: 'iphone',
      real_mobile: false
    },
    BS_InternetExplorer10: {
      base: 'BrowserStack',
      os: 'Windows',
      os_version: '8',
      browser: 'ie',
      browser_version: '10.0'
    },
    BS_InternetExplorer11: {
      base: 'BrowserStack',
      os: 'Windows',
      os_version: '10',
      browser: 'ie',
      browser_version: '11.0'
    }
  };

  let historyAlias;
  switch (process.env.TEST_ENV) {
    case 'cjs':
      historyAlias = 'cjs/history.js';
      break;
    case 'umd':
      historyAlias = 'umd/history.js';
      break;
    default:
      historyAlias = 'modules/index.js';
  }

  config.set({
    customLaunchers: customLaunchers,

    browsers: ['Chrome'],
    frameworks: ['mocha'],
    reporters: ['mocha'],

    files: ['tests.webpack.js'],

    preprocessors: {
      'tests.webpack.js': ['webpack', 'sourcemap']
    },

    webpack: {
      devtool: 'inline-source-map',
      module: {
        loaders: [
          {
            test: /\.js$/,
            exclude: /node_modules/,
            loader: 'babel-loader'
          }
        ]
      },
      resolve: {
        alias: {
          history$: path.resolve(__dirname, historyAlias)
        }
      },
      plugins: [
        new webpack.DefinePlugin({
          'process.env.NODE_ENV': JSON.stringify('test')
        })
      ]
    },

    webpackServer: {
      noInfo: true
    }
  });

  if (process.env.USE_CLOUD) {
    config.browsers = Object.keys(customLaunchers);
    config.reporters = ['dots'];
    config.concurrency = 2;

    config.browserDisconnectTimeout = 10000;
    config.browserDisconnectTolerance = 3;

    if (process.env.TRAVIS) {
      config.browserStack = {
        project: projectName,
        build: process.env.TRAVIS_BUILD_NUMBER,
        name: process.env.TRAVIS_JOB_NUMBER
      };

      config.singleRun = true;
    } else {
      config.browserStack = {
        project: projectName
      };
    }
  }
};
